package lion.framework.core.db.datasource;

import java.util.UUID;

import javax.sql.DataSource;

import lion.dev.lang.MapJ;
import lion.framework.core.db.DataSourceManager;
import lion.framework.core.db.anno.DataSourceProvider;

import com.jolbox.bonecp.BoneCPDataSource;

/**
 * bonecp 连接池提供类<br/>
 * 默认：分区为3个，每个分区最多50个连接,初始 10个连接<br/>
 * 设置：1、partitions:分区数<br/>
 * 2、helpers:帮助线程数<br/>
 * 3、alias:池名称<br/>
 * 4、这几个参数都是可选的
 *
 * <pre>
 * time   2013年8月6日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@DataSourceProvider("bonecp")
public class BoneCPDataSourceProvider implements IDataSourceProvider {

	private MapJ config;

	public BoneCPDataSourceProvider(MapJ config) {

		this.config = config;
	}

	@Override
	public DataSource getDataSource() {

		BoneCPDataSource ds = new BoneCPDataSource(); // create a new datasource
		ds.setDriverClass(DataSourceManager.getJDBCDriver(config.getString("type")));
		ds.setJdbcUrl(String.format(DataSourceManager.getDriverURLTemplate(config.getString("type", "mysql")), config.getString("server", "localhost"),
				config.getInt("port", 3306), config.getString("db"))); // set

		ds.setConnectionTestStatement("select CURRENT_TIME()");
		ds.setUsername(config.getString("user"));
		ds.setPassword(config.getString("password"));

		ds.setAcquireIncrement(config.getInt("init", 10));
		ds.setPartitionCount(config.getInt("partitions", 3));
		ds.setMaxConnectionsPerPartition(50 * ds.getPartitionCount());

		ds.setPoolName(config.getString("alias", UUID.randomUUID().toString().replace("-", "")));
		ds.setReleaseHelperThreads(config.getInt("helpers", 3));

		return ds;
	}
}
